﻿using System;
using System.Collections.Generic;
using RentalSystem.Data.EF.Core;
using System.Data.Objects;
using System.Data.Common;

namespace RentalSystem.Data.EF.Dao
{
    public class EFPagesContentsDao : IPagesContentsDao
    {
        #region Queries

        private readonly string GetQuery;
        private readonly string GetByTitleQuery;

        #endregion

        private EFManager<PagesContents> manager;

        public EFPagesContentsDao(RentalDatabaseEntities repository)
        {
            GetByTitleQuery = "SELECT VALUE pc FROM PagesContents AS pc WHERE pc.PagesContentTitle = @Title;";

            this.manager = new EFManager<PagesContents>(repository);
        }

        #region IDao1Key

        public PagesContents Add(PagesContents entity)
        {
            manager.Database.AddToPagesContents(entity);
            manager.Save();
            return entity;
        }

        public PagesContents Get(int id)
        {
            throw new NotImplementedException();
        }

        public void Delete(int id)
        {
            throw new NotImplementedException();
        }

        public void Delete(PagesContents entity)
        {
            throw new NotImplementedException();
        }

        public void Update(PagesContents entity, uint fields)
        {
            QueryParam[] parameters = new QueryParam[]
                {
                    new QueryParam("@Title", entity.PagesContentTitle)
                };

            ObjectQuery<PagesContents> result = manager.SQLQueryToEntity(GetByTitleQuery, parameters);

            foreach (var item in result)
            {
                if ((fields & (uint)PagesContentFields.Title) == (uint)PagesContentFields.Title)
                    item.PagesContentTitle = entity.PagesContentTitle;
                if ((fields & (uint)PagesContentFields.Content) == (uint)PagesContentFields.Content)
                    item.PagesContentContent = entity.PagesContentContent;
            }

            manager.Save();
        }

        public List<PagesContents> List()
        {
            throw new NotImplementedException();
        }

        #endregion

        public PagesContents GetContentByTitle(string title)
        {
            QueryParam[] parameters = new QueryParam[]
                {
                    new QueryParam("@Title", title)
                };

            ObjectQuery<PagesContents> result = manager.SQLQueryToEntity(GetByTitleQuery, parameters);
            
            foreach (var item in result)
            {
                return item;
            }

            return null;
        }
    }
}
